<?php
namespace Home\Controller;
use Think\Controller;

class UserController extends FrontController {
	public function index() {
		if (!session('用户')) {
			$this->redirect('login');
		}
		//sui
		$this->assign('title', '个人中心');
		$sui = [
			'information' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		$this->display();
	}
	public function detail() {
		if (!session('用户')) {
			$this->redirect('login');
		}
		//sui
		$this->assign('title', '个人信息');
		$sui = [
			'information' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		if (IS_POST) {
			$model = D('User');
			$upload = new \Think\Upload(); // 实例化上传类
			$upload->maxSize = 99999999; // 设置附件上传大小
			$upload->rootPath = './Public/file/'; // 设置附件上传根目录
			$upload->savePath = ''; // 设置附件上传（子）目录
			$upload->autoSub = false;
			$info = $upload->upload();
			if ($info) {
				$_POST['photo'] = $info['photo']['savename'];
				//上传成功，删除原有文件
				unlink('./Public/file/' . $user['photo']);
			}
			$_POST['id'] = session('用户')['id'];
			if (!$model->create()) {
				$this->error($model->getError());
				return false;
			}
			$model->save();
			$user = D('User')->find(session('用户')['id']);
			session('用户', $user);
			
			//刚刚登录，跳转回之前的筹单
			if (($_SESSION['lastFundingTo'])&&($_SESSION['lastFunding'])) {
				$_SESSION['lastFundingTo'] = false;
                $lastFundingId = $_SESSION['lastFunding']['id'];
                $lastConsignmentId = $_SESSION['lastFunding']['consignment_id'];
                unset($_SESSION['lastFunding']);
				$this->redirect('/Home/Funding/detail/id/'.$lastFundingId.'/consignment_id/'.$lastConsignmentId);
			}
			$this->success('更新完成!');
		}

		//用户信息
		$user = D('User')->find(session('用户')['id']);
		$this->assign('user', $user);
		$this->display();
	}
	public function login($afterLogin = '',$device='mobile') {
		//sui
		$this->assign('title', '登录');
		$sui = [
			'information' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		if (IS_POST) {
			// dump($_POST);exit;
			//用户登录
			$userModel = D('User');
			if (!($userModel->create($_POST, 4) && $userModel->login('用户'))) {
				if($device == 'pc'){
					$this->error($userModel->getError(), U('Travelgame/pclist',['mode'=>'login']));
				} else {
					$this->error($userModel->getError());
				}
			}
			if ($afterLogin == 1) {
				if($device == 'pc'){
					$this->success('登录成功！', U('Travelgame/pclist'),session('afterLogin'));
				} else {
					$this->success('登录成功!', session('afterLogin'));
				}
			} else {
				if($device == 'pc'){
					$this->success('登录成功！', U('Travelgame/pclist'));		
				} else {
					$this->redirect('User/index');
				}
			}
		}
		$this->display();
	}

	public function WxLogin() {
		if ($this->isWeixin()) {
			//微信登录
			$this->redirect('/Api/Wxlogin/index');
		} else {
			//不在微信中
			$this->error('请在微信中使用微信登录!');
		}
	}

	public function logout($device="mobile") {
		session('用户', null);
        if ($device == 'pc') {
            $this->success('注销成功!', U('Travelgame/pclist'));
        }
		$this->success('注销成功!', U('User/index'));
	}

	public function register($type='用户',$device='mobile') {
		//sui
		$this->assign('title', '注册');
		$sui = [
			'information' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		if (IS_POST) {
			//验证码
			
			if ($_POST['verify-code'] != session('verifyCode')) {
				$this->error('验证码有误,请重新填写!');
			}
	        if (D('User')->where(['username'=>$_POST['username'], 'type'=>$type])->find()) {
	            $this->error('您已经注册过，请勿重复注册!');
	        }
			//用户注册
			$model = D('User');
			$_POST['type'] = $type;
			$_POST['state'] = '正常';
			if (!$model->create()) {
				$this->error($model->getError());
				return false;
			}
			$newUserId = $model->add();
			unset($data);
			$data['principal_id'] = $newUserId;
			$data['create_time'] = time();
			if ($type == '用户') {
				if ($device == 'pc') {
					$this->success('注册成功,请登录使用!', U('Travelgame/pclist',['mode'=>'login']));
				} else {
					$this->success('注册成功,请登录使用!', U('User/index'));
				}
			}elseif ($type == '旅社') {
				//创建一个旅社用户
				D('UserClub')->add($data);
				$this->success('注册成功,将跳转到后台,请先完善资料！', U('/Club'));
			} elseif ($type == '导游') {
				//创建一个导游用户
				D('UserGuider')->add($data);
				$this->success('注册成功,将跳转到后台,请先完善资料！', U('/Guider'));
			} elseif ($type == '商家') {
				D('UserShop')->add($data);
				$this->success('注册成功,将跳转到后台,请先完善资料！', U('/Shop'));

			}
		}
		$this->display();
	}

	public function sendVerifyCode() {
		//生成四位随机验证码
		$verifyCode = mt_rand(1000, 9999);
		session('verifyCode', $verifyCode);
		//发送验证码
		$ret = \sendSms($_POST['phone'], $verifyCode);
		var_dump($verifyCode);
		echo 'success';

	}
	public function CustomizedGuider() {
		if (!session('用户')) {
            $this->redirect('login');
        }
		//sui
		$this->assign('title', '定制导游订单列表');
		$sui = [
			'information' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		//当前用户的定制导游订单列表
		$model = D('CustomizedGuider');
		$count = $model->count();
		$page = new \Think\SuiPage($count, C('PAGE_NUM'));
		$show = $page->show();
		$list = $model->order('customized_guider.id desc')->where(['user_id'=>session('用户')['id']])->limit($page->firstRow . ',' . $page->listRows)->select();
		foreach ($list as $key => $value) {
			$guider = D('UserGuider')->where(['principal_id' => $value['guider_user_id']])->find();
			$list[$key]['guider'] = $guider;
			$user = D('User')->find($value['guider_user_id']);
			$list[$key]['user'] = $user;
		}
		$this->assign('list', $list);
		$this->assign('page', $show);
		$this->display();
	}
	public function CustomizedTravel() {
		if (!session('用户')) {
            $this->redirect('login');
        }
		//sui
		$this->assign('title', '定制旅游订单列表');
		$sui = [
			'information' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		//当前用户的定制旅游订单列表
		$whereArr = ['user_id'=>session('用户')['id']];
		$model = D('CustomizedTravel');
		$count = $model->where($whereArr)->count();
		$page = new \Think\SuiPage($count, C('PAGE_NUM'));
		$show = $page->show();
		$list = $model->order('id desc')->where($whereArr)->limit($page->firstRow . ',' . $page->listRows)->select();
		//随机选择一个旅行社
		$this->assign('tel', $userClubs[$randKey]['tel']);
		foreach ($list as $key => $value) {
			if ($value['club_user_id'] == 0) {
				$userClubs = D('UserClub')->where(['bussiness'=>['LIKE', '%'.$type.'%']])->select();
				$randKey = rand(1,count($userClubs)-1);
				$list[$key]['tel'] = $userClubs[$randKey]['tel'];
			} else {
				$list[$key]['tel'] = D('UserClub')->where(['principal_id'=>$value['club_user_id']])->find()['tel'];
			}
		}
		$this->assign('list', $list);
		$this->assign('page', $show);
		$this->display();
	}

	public function notice() {
		if (!session('用户')) {
            $this->redirect('login');
        }
		//sui
		$this->assign('title', '通知列表');
		$sui = [
			'information' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		//获取当前用户的通知列表
		$whereArr = ['receive_user_id' => session('用户')['id']];
		$model = D('Notice');
		$count = $model->where($whereArr)->count();
		$page = new \Think\SuiPage($count, C('PAGE_NUM'));
		$show = $page->show();
		$list = $model->where($whereArr)->order('id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
		$this->assign('list', $list);
		$this->assign('page', $show);
		$this->display();
		//修改为已读
		foreach ($list as $key => $value) {
			$model->where(['id' => $value['id']])->data(['state' => '已读'])->save();
		}
	}

	public function FundingOrder() {
		if (!session('用户')) {
            $this->redirect('login');
        }
		//sui
		$this->assign('title', '众筹订单列表');
		$sui = [
			'information' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		//当前用户的众筹订单列表
		$model = D('FundingOrder');
		unset($whereArr);
		$whereArr['user_id'] = session('用户')['id'];
		$count = $model->where($whereArr)->count();
		$page = new \Think\SuiPage($count, C('PAGE_NUM'));
		$show = $page->show();
		$list = $model->order('id desc')->where($whereArr)->limit($page->firstRow . ',' . $page->listRows)->select();
		foreach ($list as $key => $value) {
			//funding
			$funding = D('Funding')->find($value['funding_id']);
			if ($funding['transaction_type'] == '定制') {
				//unset
				unset($list[$key]);
				//count-1
				$count--;
				continue;
			}
			$list[$key]['funding'] = $funding;
			$list[$key]['specify'] = $fundingSpecify;
			$fundingType = D('FundingType')->find($funding['funding_type']);
			$list[$key]['fundingType'] = $fundingType;
			$fundingModel = D('Funding' . ucfirst($fundingType['en']));
			$fundingSpecify = $fundingModel->where(['principal_id' => $value['funding_id']])->find();
			$list[$key]['specify'] = $fundingSpecify;
			$fundingInfo = D('Funding')->where(['id' => $value['funding_id']])->find();
			$userInfo = D('User')->where(['id'=>$fundingInfo['user_id']])->find();
			$list[$key]['tel'] = $userInfo['username'];
		}
		$this->assign('list', $list);
		$this->assign('page', $show);
		$this->display();
	}

	//找回密码
	public function findPassword() {
		//sui
		$this->assign('title', '找回密码');
		$sui = [
			'information' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		if (IS_POST) {
			//验证码
			if ($_POST['verify-code'] != session('verifyCode')) {
				$this->error('验证码有误,请重新填写!');
			}
			//重置密码
			$user = D('User')->where(['username'=>$_POST['username']])->find();
			if (!$user) {
				$this->error('手机号码不存在,请先注册!');
				return false;
			} 
			if ($_POST['password'] != $_POST['repassword']) {
				$this->error('密码和重复密码不一致!');
				return false;
			}
			//更新密码
			D('User')->where(['username'=>$_POST['username']])->data(['password'=>password_hash($_POST['password'], PASSWORD_BCRYPT)])->save();
			$this->success('操作成功!', U('User/login'));
		}
		$this->display();
	}

}
